package com.woniuxy.project115.kaer.mall.consumer;

import cn.hutool.json.JSONUtil;
//import com.alipay.api.AlipayClient;
//import com.alipay.api.request.AlipayTradeQueryRequest;
import com.woniuxy.project115.kaer.mall.entity.ProductOrderInfo;
import com.woniuxy.project115.kaer.mall.mapper.ProductOrderInfoMapper;
import com.woniuxy.project115.kaer.mall.service.ProductOrderInfoService;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Component
public class CheckOrderConsumer {
    @Resource
    private ProductOrderInfoService productOrderInfoService;
    @Resource
    private ProductOrderInfoMapper productOrderInfoMapper;
//    @Resource
//    private AlipayClient alipayClient;
    @RabbitListener(bindings = @QueueBinding(
            value=@Queue(name="check_order_queue"),
            exchange = @Exchange(name="de2"),
            key = "check_order"
    ))
    @RabbitHandler
    public void checkOrder(String orderNum)throws Exception {
        System.out.println("时间到检查订单状态:"+orderNum);
//        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
//        alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderNum+"\"}");
//        String result = alipayClient.execute(alipayRequest).getBody();
//        System.out.println(result);
//        String orderInfo= JSONUtil.parseObj(result).get("alipay_trade_query_response").toString();
//        String payCode=JSONUtil.parseObj(orderInfo).get("code").toString();
        ProductOrderInfo orderInfo = productOrderInfoMapper.selectById(orderNum);
        String payCode = "00000";
        if (orderInfo.getPayState().equals("已支付")) {
             payCode = "10000";
        }
        if("10000".equals(payCode)){
//            String tradeStatus = JSONUtil.parseObj(orderInfo).get("trade_status").toString();
            String tradeStatus="TRADE_SUCCESS";
            if("TRADE_SUCCESS".equals(tradeStatus)){
//                String payTime = JSONUtil.parseObj(orderInfo).get("send_pay_date").toString();
                String payTime="";
                //用户已经完成支付
                productOrderInfoService.updateOrder(orderNum,payTime);
                return;
            }
        }
        //表示未支付成功(0为超时未支付自动取消,1为用户主动取消)
        productOrderInfoService.cancelOrder(orderNum,0);
    }
}
